/**
 * 
 */
package com.geezdata.cps.ttk.core.command;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.geezdata.cps.base.constant.Constants;
import com.geezdata.cps.base.response.BaseResponse;
import com.geezdata.cps.cqrs.command.Command;
import com.geezdata.cps.ttk.common.request.CreateOrUpdateOrderSyncTaskRequest;
import com.geezdata.cps.ttk.domain.domain.OrderSyncTask;
import com.geezdata.cps.ttk.mapper.mapper.OrderSyncTaskMapper;

/**
 * @author sszheng
 * @date 创建时间：2018年6月19日 下午4:57:40
 *
 */
@Service
public class CreateOrUpdateOrderSyncTaskCommand implements Command<CreateOrUpdateOrderSyncTaskRequest, Object> {
	@Autowired
	private OrderSyncTaskMapper orderSyncTaskMapper;
	
	@Override
	@Transactional
	public BaseResponse<Object> execute(CreateOrUpdateOrderSyncTaskRequest request) {
		Date now = new Date();
		Integer startTime = getStartTime();
		Integer endTime = ((int)(System.currentTimeMillis()/ 1000)) - 10;
		OrderSyncTask task = newInstance(startTime, endTime, now);
		
		orderSyncTaskMapper.insert(task);
		return BaseResponse.success(null);
	}
	
	private Integer getStartTime() {
		OrderSyncTask last = orderSyncTaskMapper.selectLast();
		Integer startTime = null;
		if(last != null ) {
			startTime = last.getEndTime();
		} else {
			startTime = (int)((System.currentTimeMillis() - 30 * Constants.ONE_DAY_SECOND * 1000) /1000);
		}
		return startTime;
	}

	private OrderSyncTask newInstance(Integer startTime, Integer endTime, Date now) {
		OrderSyncTask task = new OrderSyncTask();
		task.setStartTime(startTime);
		task.setEndTime(endTime);
		task.setStatus(0);
		task.setCreatedAt(now);
		task.setUpdatedAt(now);
		return task;
	}

}
